/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionMoveOwnerActivity.java   
 * @Package com.jiyi.activity.supervision   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-18 下午4:15:21   
 * @version V1.0     
 */  
package com.jiyi.activity.supervision;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.supervision.SupervisionOwnerDetailJson;
import com.jiyi.bean.weibao.CompanyBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.SupervisionOwnerEvent;
import com.jiyi.inteface.OwnerMovePopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.OwnerMovePopView;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

/**   
 * @ClassName:  SupervisionMoveOwnerActivity   
 * @Description:TODO(转移分配业主)   
 * @author: HYM  
 * @date:   2017-10-18 下午4:15:21   
 *      
 */
public class SupervisionMoveOwnerActivity extends ActivityBase implements OnRefreshListener , OwnerMovePopInterface{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.etSearch)
	EditText etSearch;
	
	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	ViewGroup container;
	private List<CompanyBean> dataList = new ArrayList<CompanyBean>();
	//监管大队的id,name
	String supervision_id,supervision_name;
	OwnerMovePopView mOwnerMovePopView;
	Dialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supersivion_move_owner);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}
	
	private void init() {
		inflater = LayoutInflater.from(this);
		getIntentData();
		initViewState();
		setTop();
		setAdapter();
		getData();
		mOwnerMovePopView = new OwnerMovePopView(this,this);
	}
	
	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					getData();
					return true;
				}
				return false;
			}
		});
		
	}
	
	private void getIntentData() {
		supervision_id = getIntent().getStringExtra("supervision_id");
		supervision_name = getIntent().getStringExtra("supervision_name");
	}

	private void setTop() {
		tvTitle.setText("转移管理");
		tvSearch.setVisibility(View.GONE);
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(this));
		mListView.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));

		CommonAdapter mCommonAdapter = new CommonAdapter<CompanyBean>(
				this, R.layout.item_supervision_owner_move, dataList) {
			@Override
			protected void convert(ViewHolder holder,
					final CompanyBean t, final int position) {
				holder.setText(R.id.tvOwnerName, t.getName());
				holder.setText(R.id.tvOwnerDate, t.getPhone());
				holder.setText(R.id.tvOwnerAddress, t.getAddress());
				holder.setImage(R.id.ivLogo, t.getCompany_logo() == null ? ""
						: t.getCompany_logo());
				holder.setOnClickListener(R.id.tvMove, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						getOwnerDetail(t.getId(),position);
					}
				});
			}
		};

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mListView, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onRefresh() {
		getData();
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		if (!TextUtils.isEmpty(etSearch.getText().toString())) {
			params.put("com_name", etSearch.getText().toString());
		}
		
		String url ;
		if (UserInfoUtil.getCurrentUserSupervisionRole() == 1) {
			url = WebApi.SUPERVISION_BUSI_OWNER_LIST;
		}
		else {
			url = WebApi.SUPERVISION_SELF_UNITS;
		}
		
		VolleyRequest.StringRequestPost(this,
				url, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<CompanyBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<CompanyBean>>() {
												}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@OnClick({ R.id.tvBack})
	public void onClick(View view) {
		Intent intent ;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		default:
			break;
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getHuoDongDetail   
	 * @Description: TODO(获取业主详情)   
	 * @param huoDongId void 
	 * @date: 2017-7-17
	 */  
	void getOwnerDetail(final String ownerId,final int position)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", ownerId);
		params.put("jg_role_id", UserInfoUtil.getCurrentUserSupervisionRole()+"");

		dialog = showDialog(dialog);
		
		VolleyRequest.StringRequestPost(this, WebApi.SUPERVISION_OWNER_MOVE_DETAIL, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								SupervisionOwnerDetailJson temp = new Gson().fromJson(
										result, SupervisionOwnerDetailJson.class);
								
								mOwnerMovePopView.showPopWindow(temp.getData(),ownerId,position);
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
	
	/**   
	 * @author: HYM 
	 * @Title: doPost   
	 * @Description: TODO(转移)   
	 * @param supervised_id 接收方的监管id
	 * @param id 当前业主id
	 * @param position void 
	 * @date: 2017-10-19
	 */  
	void doPost(String supervised_id,final String id,final int  position)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("receiver_id", supervised_id);

		dialog = showDialog(dialog);
		
		VolleyRequest.StringRequestPost(this, WebApi.SUPERVISION_OWNER_MOVE_SUBMIT, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
//								dataList.remove(position);
//								adapter.notifyDataSetChanged();
								mOwnerMovePopView.hidePopWindow();
//								EventBus.getDefault().post(new SupervisionOwnerEvent(1,id));
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	@Override
	public void OnSureListener(String supervision_id,String ownerId,int position) {
		doPost(supervision_id, ownerId, position);
	}
	
}
